package task

import (
	//"../dockerclient"
	"fmt"
	"time"
	"strconv"
	"path/filepath"
	"encoding/json"
	"errors"
	"os"
	"io/ioutil"
)

import (
	"../config"
)

//var conf config.Config

//type JobSheet struct {
//	GroupName string
//	JobList []Job
//}

func TaskSheetCreate(task string) (TaskStatus, error) {
	conf := config.Conf
	//var now = strconv.Itoa(int(time.Now().Unix()))
	//var tasksheet = JobSheet{GroupName:"group-"+now}
	//var job = Job{JobName:"jobtest",TaskId:now,TaskStartedAt:now,TaskStatus:"created"}
	//tasksheet.JobList = append(tasksheet.JobList,job)
	fmt.Println("in TaskSheetCreate, CONF: ", conf)
	//fmt.Println(tasksheet)
	//groupCreate(tasksheet,task)
	//dockerclient.DockerClient{}

	return taskCreate(task)
}

func taskCreate(task string) (TaskStatus, error) {

	var taskstatus TaskStatus
	err := json.Unmarshal([]byte(task), &taskstatus)
	if err != nil {
		return TaskStatus{}, errors.New("get name from body error.")
	}
	now := time.Now().Unix()

	if taskstatus.Name == "" {
		taskstatus.Name = "etl-service-" + strconv.Itoa(int(now))
	}
	jobpath := filepath.Join(config.Conf.WorkSpacePath, taskstatus.Name)
	os.MkdirAll(jobpath, os.ModePerm)

	configpath := filepath.Join(jobpath, "config.json")
	ioutil.WriteFile(configpath, []byte(task), os.ModePerm)

	statuspath := filepath.Join(jobpath, "status.json")
	taskstatus.Id = strconv.Itoa(int(now))
	taskstatus.Status = "created"
	taskstatus.CreatedAt = time.Unix(now, 0).Format("2006-01-02 03:04:05 PM")
	status, _ := json.Marshal(taskstatus)
	ioutil.WriteFile(statuspath, status, os.ModePerm)

	return taskstatus, err
}

//func groupCreate(tasksheet JobSheet, task string) error{
//
//	grouppath := filepath.Join(config.Conf.WorkSpacePath, tasksheet.GroupName)
//	os.MkdirAll(grouppath,os.ModePerm)
//	for _, task := range tasksheet.JobList{
//		jobpath := filepath.Join(grouppath,task.TaskId)
//		os.MkdirAll(jobpath, os.ModePerm)
//
//		configpath := filepath.Join(jobpath,"config.json")
//		ioutil.WriteFile(configpath,[]byte(task),os.ModePerm)
//
//		statuspath := filepath.Join(jobpath, "status.json")
//		ioutil.WriteFile(statuspath, []byte("{\"Status\":\"created\"}"), os.ModePerm)
//	}
//
//	return nil
//}
